package org.test.testapi.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.test.testapi.entity.MessageResult;

/**
 * @author xlang
 * @version 0.0.1
 * @desciption
 * @date 2020/9/5 14:08
 */
@Slf4j
@RestControllerAdvice
public class ExceptionControllerAdvice {

    /**
     * 拦截参数异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public MessageResult myErrorHandler(BindException e) {
        String errMsg = e.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
        log.info("参数绑定异常= {}", errMsg);
        return MessageResult.error(errMsg);
    }

    /**
     * 拦截参数异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    public MessageResult myErrorHandler(IllegalArgumentException e) {
        log.info("拦截参数异常={}",e);
        MessageResult result = MessageResult.error(e.getMessage());
        return result;
    }

    /**
     * 拦截绑定参数异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServletRequestBindingException.class)
    public MessageResult myErrorHandler(ServletRequestBindingException e) {
        log.info("拦截绑定参数异常={}",e);
        MessageResult result = MessageResult.error(3000, "请求参数异常,请检查是否缺少必要参数或则参数错误!");
        return result;
    }

    /**
     * 拦截异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public MessageResult myErrorHandler(Exception ex) {
        log.info("拦截异常={}",ex);
        MessageResult result = MessageResult.error("未知错误");
        return result;
    }

    /**
     * @param
     * @return
     * @author MrGao
     * @description 错误请求方式异常  HttpRequestMethodNotSupportedException
     * @date 2018/2/28 17:32
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public MessageResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        log.info("错误请求方式异常={}",ex);
        String methods = "";
        //支持的请求方式
        String[] supportedMethods = ex.getSupportedMethods();
        for (String method : supportedMethods) {
            methods += method;
        }
        MessageResult result = MessageResult.error("Request method " + ex.getMethod() + "  not supported !" +
                " supported method : " + methods + "!");
        return result;
    }
}
